﻿using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WebApiMIT3.Models;
using WebApiMIT3.Utils;

namespace WebApiMIT3.BusinessLayer
{
    public class CategoryService
    {
        private int addCategoryMinimum = Config.CategoryService_MinimumCheck;

        public CategoryService()
        {
            XMLHandler.GetCategoriesFromXML();
        }

        /// <summary>
        /// Finds a category for the given dataModel based on the words in the Lists in categoryModel.
        /// </summary>
        /// <param name="dataModel">Datamodel without categories.</param>
        /// <returns>a datamodel with (if found) one or more categories.</returns>
        public async Task FindCategory(DataModel dataModel)
        {
            await Task.Run(() =>
            {
                var categoryCounter = new Dictionary<string, int>();
                var propertylist = typeof(CategoryModel).GetProperties();
                foreach (var property in propertylist) // Looping the Lists in CategoryModel 
                {
                    var i = 0;
                    var wordList = (List<string>)property.GetValue(null);
                    foreach (var word in wordList) // Looping the strings in the Lists from Categorymodel
                    {
                        // Looping every word in the FullDescription to find a match with the word in wordList.
                        foreach (Match match in Regex.Matches(dataModel.FullDescription.ToLower(), word.ToLower())) 
                        {
                            i++;
                        }

                        foreach (Match match in Regex.Matches(dataModel.SummaryDescription.ToLower(), word.ToLower()))
                        {
                            i++;
                        }

                        foreach (Match match in Regex.Matches(dataModel.Title.ToLower(), word.ToLower()))
                        {
                            i++;
                        }
                    }

                    categoryCounter.Add(property.Name, i);
                }

                foreach (var item in categoryCounter)
                {
                    if (item.Value >= this.addCategoryMinimum)
                    {
                        dataModel.Categories.Add(item.Key);
                    }
                }
            });
        }
    }
}